package com.cdgeekcamp.redas.wechat.controller;

import com.cdgeekcamp.redas.wechat.entity.WeChatResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class WeChatErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "No Mapping Found";
    }

    @RequestMapping(value = "/error")
    @ResponseBody
    public WeChatResponse error(HttpServletRequest request) {
        return getStatus(request);
    }

    private WeChatResponse getStatus(HttpServletRequest request) {
        WeChatResponse weChatResponse = new WeChatResponse();
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

        if (statusCode != null) {
            try {
                weChatResponse.setStatusCode(statusCode);
                weChatResponse.setHttpStatus(HttpStatus.valueOf(statusCode));
                return weChatResponse;
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        weChatResponse.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        return weChatResponse;
    }
}
